import React, { useState } from 'react';
import useSpeechRecognition from '../hooks/useSpeechRecognition';
import ShareButton from './ShareButton';
import RuleEditor from './RuleEditor';
import { defaultRules } from '../utils/translationRules';

interface TranslationRule {
  id: string;
  pattern: string;
  meaning: string;
}

const Translator: React.FC = () => {
  const [inputText, setInputText] = useState('');
  const [translatedText, setTranslatedText] = useState('');
  const [rules, setRules] = useState<TranslationRule[]>(defaultRules);
  const [showRuleEditor, setShowRuleEditor] = useState(false);
  
  const {
    isListening,
    startListening,
    stopListening,
    hasRecognitionSupport
  } = useSpeechRecognition({
    onResult: (result) => setInputText(result)
  });

  const handleTranslate = () => {
    if (!inputText.trim()) {
      setTranslatedText("请输入女朋友说的话");
      return;
    }
    
    const matchedRule = rules.find(rule => 
      new RegExp(rule.pattern, 'i').test(inputText)
    );
    
    if (matchedRule) {
      setTranslatedText(`"${inputText}" 的潜台词是: ${matchedRule.meaning}`);
    } else {
      setTranslatedText(`无法识别"${inputText}"的潜台词，可能她真的是字面意思...`);
    }
  };

  const handleVoiceInput = () => {
    if (isListening) {
      stopListening();
    } else {
      startListening();
    }
  };

  const handleClear = () => {
    setInputText('');
    setTranslatedText('');
  };

  const addNewRule = (newRule: Omit<TranslationRule, 'id'>) => {
    setRules([...rules, { ...newRule, id: Date.now().toString() }]);
    setShowRuleEditor(false);
  };

  return (
    <div className="translator-container">
      <h1>女朋友说话翻译器 💖</h1>
      <p className="subtitle">听懂她的潜台词，恋爱不翻车</p>
      
      <div className="input-section">
        <textarea
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          placeholder="输入女朋友说的话..."
          rows={4}
        />
        
        <div className="button-group">
          {hasRecognitionSupport && (
            <button 
              onClick={handleVoiceInput}
              className={isListening ? 'listening' : ''}
            >
              {isListening ? '🎤 识别中...' : '🎤 语音输入'}
            </button>
          )}
          
          <button onClick={handleTranslate} disabled={!inputText.trim()}>
            🔍 翻译潜台词
          </button>
          
          <button onClick={handleClear} disabled={!inputText && !translatedText}>
            🗑️ 清空
          </button>
        </div>
      </div>
      
      {translatedText && (
        <div className="result-section">
          <h3>翻译结果:</h3>
          <p>{translatedText}</p>
          
          <div className="share-section">
            <ShareButton 
              text={translatedText} 
              inputText={inputText}
            />
          </div>
        </div>
      )}
      
      <div className="action-buttons">
        <button onClick={() => setShowRuleEditor(true)}>
          ✏️ 添加自定义规则
        </button>
      </div>
      
      {showRuleEditor && (
        <RuleEditor 
          onSave={addNewRule} 
          onClose={() => setShowRuleEditor(false)}
        />
      )}
      
      <div className="rules-section">
        <h3>📚 当前翻译规则库 ({rules.length}条)</h3>
        <ul>
          {rules.slice(0, 5).map(rule => (
            <li key={rule.id}>
              <strong>"{rule.pattern}"</strong> → {rule.meaning}
            </li>
          ))}
        </ul>
        {rules.length > 5 && <p>...以及{rules.length - 5}条更多规则</p>}
      </div>
    </div>
  );
};

export default Translator;